package com.gochic;

import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.gochic.DataEntity;
import com.gochic.DataUtil;

public abstract class MidObject implements Serializable {
	private static final long serialVersionUID = 3937627568104450079L;
	private DataEntity entity;
	
	protected MidObject() {
	}

	protected MidObject(DataEntity de) {
		entity = de;
	}

	protected DataEntity saveEntity() {
		PersistenceManager pm = DataUtil.getPersistenceManager();
		DataEntity result = null;
        try {
        	DataEntity de = (DataEntity)this.getEntity();
        	de.setEditTime();
            result = pm.makePersistent( de );
        } finally {
            pm.close();
        }
        return result;
	}
	
	@SuppressWarnings("unchecked")
	protected DataEntity getEntityById( int id ) {
		PersistenceManager pm = DataUtil.getPersistenceManager();
		Query query = pm.newQuery(DataEntity.class);
		query.setFilter( "id == " + id );
		
		List<DataEntity> des = new ArrayList<DataEntity>(0);
		try {
			des = (List<DataEntity>) query.execute();
		} finally {
			pm.close();
		}
		if( des != null && des.size() > 0 )
			return des.get(0);
	    return null;
	}
	
	public void remove() {
		PersistenceManager pm = DataUtil.getPersistenceManager();
		try {
			pm.deletePersistent(this.entity);
		} finally {
			pm.close();
		}
	}

	public int getId() {
		return this.entity.getId();
	}

	public Date getEditTime() {
		return this.entity.getEditTime();
	}

	public String getEditTimeString() {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		return df.format( this.entity.getEditTime() );
	}
	
	public DataEntity getEntity() {
		return this.entity;
	}

	protected void setEntity(DataEntity de) {
		this.entity = de;
	}

	public void setEditTime(Date editTime) {
		this.entity.setEditTime(editTime);
	}
	
	public void setEditTime() {
		this.entity.setEditTime();
	}
}
